package com.wwj.utils;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/*
 * 图片处理工具类
 */
public class CompressPic {

    /*******************************************************************************
     * 缩略图类（通用） 本java类能将jpg、bmp、png、gif图片文件，进行等比或非等比的大小转换。 具体使用方法
     * compressPic(大图片路径,生成小图片路径,大图片文件名,生成小图片文名,生成小图片宽度,生成小图片高度,是否等比缩放(默认为true))
     */
    private File file = null; //文件对象
    private String inputDir; // 输入图路径
    private String outputDir; // 输出图路径
    private String inputFileName; // 输入图片名称
    private String outputFileName; // 输出图片名称
    private int outputWidth = 100; // 输出图片宽度
    private int outputHeight = 100; // 输出图片高度
    private boolean proportion = true; // 是否等比缩放标记(默认为等比缩放)
    private boolean isSizeCompress = false; // 是否压缩文件大小标记(默认不压缩)

    public CompressPic() { // 初始化变量
        inputDir = "";
        outputDir = "";
        inputFileName = "";
        outputFileName = "";
        outputWidth = 100;
        outputHeight = 100;
        isSizeCompress = false;
    }

    public void setInputDir(String inputDir) {
        this.inputDir = inputDir;
    }

    public void setOutputDir(String outputDir) {
        this.outputDir = outputDir;
    }

    public void setInputFileName(String inputFileName) {
        this.inputFileName = inputFileName;
    }

    public void setOutputFileName(String outputFileName) {
        this.outputFileName = outputFileName;
    }

    public void setOutputWidth(int outputWidth) {
        this.outputWidth = outputWidth;
    }

    public void setOutputHeight(int outputHeight) {
        this.outputHeight = outputHeight;
    }

    public void setWidthAndHeight(int width, int height) {
        this.outputWidth = width;
        this.outputHeight = height;
    }

    /*
     *  获得图片大小 传入参数 String path ：图片路径
     */
    public long getPicSize(String path) {
        file = new File(path);
        return file.length();
    }

    // 图片处理
    public String compressPic(/*String inputDir,String outputDir, String inputFileName,
            String outputFileName*/) {
			/*//输入图片路径
			this.inputDir = inputDir;
			//输出图片路径
			this.outputDir = outputDir;
			// 输入图片名称
			this.inputFileName = inputFileName;
			// 输出图片名称
			this.outputFileName = outputFileName;*/
        try {
            // 获得源文件
            file = new File(inputDir);
            //System.out.println(inputDir + inputFileName);
            if (!file.exists()) {
                //throw new Exception("文件不存在");
            }
            Image img = ImageIO.read(file);
            // 判断图片格式是否正确
            if (img.getWidth(null) == -1) {
                System.out.println(" can't read,retry!" + "<BR>");
                return "no";
            } else {
                int newWidth;
                int newHeight;
                // 判断是否是等比缩放
                if (this.proportion == true) {
                    // 为等比缩放计算输出的图片宽度及高度
                    double rate1 = ((double) img.getWidth(null))
                            / (double) outputWidth + 0.1;
                    double rate2 = ((double) img.getHeight(null))
                            / (double) outputHeight + 0.1;
                    // 根据缩放比率大的进行缩放控制
                    double rate = rate1 > rate2 ? rate1 : rate2;
                    newWidth = (int) (((double) img.getWidth(null)) / rate);
                    newHeight = (int) (((double) img.getHeight(null)) / rate);
                } else {
                    newWidth = outputWidth; // 输出图片宽度
                    newHeight = outputHeight; // 输出图片高度
                }
                BufferedImage tag = new BufferedImage((int) newWidth,
                        (int) newHeight, BufferedImage.TYPE_INT_RGB);

				/*
				 * Image.SCALE_SMOOTH 的缩略算法 生成缩略图片的平滑度的 优先级比速度高 生成的图片质量比较好 但速度慢
				 */
                tag.getGraphics().drawImage(
                        img.getScaledInstance(newWidth, newHeight,
                                Image.SCALE_SMOOTH), 0, 0, null);

                //处理压缩文件大小
                if (isSizeCompress) {
                    ImageWriteParam imgWriteParams;
                    imgWriteParams = new javax.imageio.plugins.jpeg.JPEGImageWriteParam(
                            null);
                    // 要使用压缩，必须指定压缩方式为MODE_EXPLICIT
                    imgWriteParams.setCompressionMode(imgWriteParams.MODE_EXPLICIT);
                    // 这里指定压缩的程度，参数qality是取值0~1范围内，
                    imgWriteParams.setCompressionQuality((float) 1);
                    imgWriteParams.setProgressiveMode(imgWriteParams.MODE_DISABLED);
                    ColorModel colorModel = tag.getColorModel();// ColorModel.getRGBdefault();
                    // 指定压缩时使用的色彩模式
                    imgWriteParams.setDestinationType(new javax.imageio.ImageTypeSpecifier(
                            colorModel, colorModel.createCompatibleSampleModel(16, 16)));
                    ImageWriter imgWrier;
                    imgWrier = ImageIO.getImageWritersByFormatName("jpg").next();
                    imgWrier.reset();
                    FileOutputStream out = new FileOutputStream(outputDir
                            + outputFileName);
                    imgWrier.setOutput(ImageIO.createImageOutputStream(out));
                    imgWrier.write(null, new IIOImage(tag, null, null), imgWriteParams);
                    out.flush();
                    out.close();
                } else {

                    File f = new File(outputDir);
                    if (!f.exists()) {
                        f.mkdirs();
                    }
                    FileOutputStream out = new FileOutputStream(outputDir
                            + outputFileName);

                    // JPEGImageEncoder可适用于其他图片类型的转换
                    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
                    encoder.encode(tag);
                    out.close();
                }

            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return outputFileName;
    }

    public String compressPicReset(String inputDir, String outputDir,
                                   String inputFileName, String outputFileName, int width, int height,
                                   boolean gp) {
        return compressPicReset(inputDir, outputDir, inputFileName, outputFileName, width, height, gp, false);
    }

    public String compressPicReset(String inputDir, String outputDir,
                                   String inputFileName, String outputFileName, int width, int height,
                                   boolean gp, boolean isSizeCompress) {
        // 输入图片路径
        this.inputDir = inputDir;
        //输出图片路径
        this.outputDir = outputDir;
        //输入图片名称
        this.inputFileName = inputFileName;
        // 输出图片名称
        this.outputFileName = outputFileName;
        //设置图片宽和高
        setWidthAndHeight(width, height);
        // 是否是等比缩放 标记
        this.proportion = gp;
        // 是否等质量压缩大小(小图不按等质量压缩大小,后果反而增大, 仅使用等比缩放即可)
        this.isSizeCompress = isSizeCompress;
        return compressPic();
    }


    public final static void pressImage(String pressImg, String targetImg, int state) {
        try {
            //目标文件
            File _file = new File(targetImg);
            Image src = ImageIO.read(_file);
            int wideth = src.getWidth(null);
            int height = src.getHeight(null);
            BufferedImage image = new BufferedImage(wideth, height,
                    BufferedImage.TYPE_INT_RGB);
            Graphics g = image.createGraphics();
            g.drawImage(src, 0, 0, wideth, height, null);

            System.out.println("img===============" + pressImg);
            //水印文件
            File _filebiao = new File(pressImg);
            System.out.println("img1===============" + _filebiao);
            Image src_biao = ImageIO.read(_filebiao);
            int wideth_biao = src_biao.getWidth(null);
            int height_biao = src_biao.getHeight(null);
            if (state == 0) {
                if (wideth == 640) {
                    g.drawImage(src_biao, (wideth - wideth_biao),
                            (height - height_biao), wideth_biao, height_biao, null);
                } else if (wideth < 640) {
                    g.drawImage(src_biao, (wideth - wideth_biao),
                            (height - height_biao), wideth_biao, height_biao, null);

                }

            } else if (state == 1) {
                g.drawImage(src_biao, (wideth - wideth_biao) + wideth_biao / 2,
                        (height - height_biao) + height_biao / 2, wideth_biao / 2, height_biao / 2, null);
            }

            //水印文件结束
            g.dispose();
            FileOutputStream out = new FileOutputStream(targetImg);
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            encoder.encode(image);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
